package com.alison.datastream.workcount;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author alison
 * @Date 2024/4/8 13:38
 * @Version 1.0
 * @Description
 */
public class S1_StreamWCForSocket {

    public static void main(String[] args) throws Exception {
        // 创建流处理执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度，默认值 = 当前计算机的CPU逻辑核数,设置成1 即单线程处理
        env.setMaxParallelism(1);
        // 从文件中读取数据
        DataStreamSource<String> inputDataStream = env.socketTextStream("192.168.56.101", 9999);
        DataStream<Tuple2<String, Long>> flatMapDataStream = inputDataStream.flatMap((line, out) -> out.collect(Tuple2.of(line.split("\\s+")[0], 1L)));
        DataStream<Tuple2<String, Long>> resultStream = flatMapDataStream.keyBy(0).sum(1);
        resultStream.print();

        // 执行任务
        env.execute();
    }
}
